import * as Cesium from '@cesium/Source/Cesium.js';
import createGroundRectangle from "./createGroundRectangle"

const defaultOptions = {
  position: [0, 0, 0],
  origin: [0.5, 0.5],
  rotation: 0,
  width: 1000,
  height: 1000,
  canvasWidth: 512,
  canvasHeight: 512,
  show: true,
  color: [1, 1, 1, 1],
  imageUrl: ''
};

class CustomGroundRectangle {
  constructor(viewer, options) {
    this.viewer = viewer;
    this.options = {
      ...defaultOptions,
      ...options
    }

    this._scratchColor = new Cesium.Color();

    this.init();
  }

  get show() {
    return this.options.show
  }
  set show(val) {
    this.options.show = val
  }

  init() {
    this.updateTexture()
    this.updateTexture2()
    this.updateCanvas()
    this.updateGroundPrimitive();
    this.updateGroundPrimitive2();
    this.updateImage();
  }

  updateTexture() {
    const _this = this;
    const options = this.options
    _this._texture && _this._texture.destroy();
    _this._texture = new Cesium.Texture({
      context: _this.viewer.scene.context,
      width: options.canvasWidth,
      height: options.canvasHeight,
      flipY: true
    });
  };

  updateTexture2() {
    const _this = this;
    var texture = _this._texture;
    _this._groundPrimitive && (_this._groundPrimitive.appearance.material.uniforms.image = texture);
  }

  updateCanvas() {
    const _this = this;
    const options = this.options
    if (!_this._canvas) {
      var canvas = document.createElement('canvas');
      _this._canvas = canvas;
      _this._ctx = canvas.getContext('2d');
    }

    _this._canvas.width = options.canvasWidth;
    _this._canvas.height = options.canvasHeight;
  };

  updateGroundPrimitive() {
    const _this = this;
    const options = this.options
    const scene = this.viewer.scene

    if (_this._groundPrimitive) {
      scene.groundPrimitives.remove(_this._groundPrimitive);
      _this._groundPrimitive = undefined;
    }

    var classificationType = Cesium.ClassificationType.BOTH;
    // const minHeight = 0;
    // const maxHeight = 0;
    var image = undefined;
    var color = undefined;
    const {
      origin:[ox, xy],
      rotation,
      position,
      width,
      height
    } = options;
    // const groundPrimitive = Cesium.createXbsjGroundPrimitive(center, this.width, this.height, this.rotation, image, color, minHeight, maxHeight, classificationType);
    var groundPrimitive = createGroundRectangle(position, width, height, ox, xy, rotation, image, color,
      classificationType);

    _this._texture && (groundPrimitive.appearance.material.uniforms.image = _this._texture);

    ['red', 'green', 'blue', 'alpha'].forEach(function(v, i) {
      return _this._scratchColor[v] = options.color[i];
    });
    groundPrimitive.appearance.material.uniforms.color = _this._scratchColor;

    _this._groundPrimitive = scene.groundPrimitives.add(groundPrimitive);
  };

  // 修复贴地面不停地更新时，不能隐藏
  updateGroundPrimitive2() {
    const _this = this;
    _this._groundPrimitive && (_this._groundPrimitive.show = _this.show);
  };

  // 这种方式没法处理crossOrigin的情况，换成Cesium的加载方式，Cesium内部会处理好Image图像的加载
  // const updateImage = () => {
  //     if (this.imageUrl) {
  //         this._myImage = this._myImage || new Image();
  //         this._myImage.src = this.imageUrl;
  //         this._myImage.onload = () => {
  //             this.canvasWidth = this._myImage.naturalWidth;
  //             this.canvasHeight = this._myImage.naturalHeight;
  //             this.drawCanvas(ctx => {
  //                 ctx.clearRect(0, 0, this._myImage.naturalWidth, this._myImage.naturalHeight);
  //                 ctx.drawImage(this._myImage, 0, 0);
  //             });
  //         }
  //     }
  // };
  updateImage() {
    const _this = this;
    const options = this.options

    if (_this._imageSubscription) {
      _this._imageSubscription.unsubscribe();
      _this._imageSubscription = undefined;
    }

    if (options.imageUrl) {
      var _observable = new rxjs.Observable(function(observer) {
        Cesium.Resource.createIfNeeded(options.imageUrl).fetchImage().then(function(image) {
          observer.next(image);
        });
      });

      _this._imageSubscription = _observable.subscribe(function(image) {
        _this.canvasWidth = image.naturalWidth;
        _this.canvasHeight = image.naturalHeight;
        _this.drawCanvas(function(ctx) {
          ctx.clearRect(0, 0, image.naturalWidth, image.naturalHeight);
          ctx.drawImage(image, 0, 0);
        });
        _this._innerImage = image;
      });
    }
  };

  drawCanvas(drawFun) {
    const {
      canvasWidth,
      canvasHeight
    } = this.options
    if (canvasWidth > 0 && canvasHeight > 0) {
      drawFun(this._ctx);
      const source = this._canvas;
      this._texture.copyFrom({
        source
      });
    } else {
      console.warn('canvas尺寸未设置，无法绘制！');
    }
  }

  flyTo() {
    const {
      width,
      height,
      position
    } = this.options
    var radius = Math.sqrt(width * width + height * height);
    this.viewer.camera.flyTo(position, radius * 3.0);
  }
}


export default CustomGroundRectangle;
